<template>
  <div v-loading="formLoading" class="formBox">
    <el-form ref="form" class="formTable p-rem-t-8 p-rem-b-80" :model="form" :rules="rules" label-width="13rem">
      <div class="cardContent">
        <el-row class="formRow">
          <el-col :span="12">
            <el-form-item label="角色名称：" prop="roleName">
              <el-input v-model.trim="form.roleName" placeholder="请输入角色名称" show-word-limit maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符：" prop="roleKey">
              <el-input v-model.trim="form.roleKey" placeholder="请输入权限字符" show-word-limit maxlength="100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色顺序：" prop="roleSort">
              <el-input v-model.trim="form.roleSort"
                        placeholder="请输入角色顺序" show-word-limit maxlength="4"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model.trim="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{
                  dict.dictLabel
                }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="是否关联项目：" prop="weatherProject">
              <el-radio-group v-model.trim="form.weatherProject">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="菜单权限：" prop="name">
              <div style="display: flex;">
                <el-checkbox v-model.trim="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                <el-checkbox v-model.trim="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
                </el-checkbox>
                <el-checkbox v-model.trim="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
                </el-checkbox>
              </div>
              <el-tree ref="menu" class="tree-border" :data="menuOptions" show-checkbox node-key="id"
                       :check-strictly="!form.menuCheckStrictly" empty-text="暂无数据" :props="defaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="formBtn m-px-b-0">
      <el-button type="primary" size="small" @click="submitForm">保存</el-button>
      <el-button size="small" @click="resetFormMixins">取消</el-button>
    </div>
  </div>
</template>
<script>
// api
import { methodGetApi } from '@/api/publicApi'
// 混入
import { formMixins } from '@/mixins/publicMixins/formMixins'
// ---------------------------------------------------------------------------------------
export default {
  mixins: [formMixins],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      menuOptions: [],
      menuExpand: false,
      menuNodeAll: false,
      form: {
        type: '',
        status: '1',
        weatherProject: '0',
        systemCode: undefined
      },
      roleMenu: null, // 根据角色ID查询菜单树结构
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '角色顺序只能输入数字', trigger: 'blur' }
        ],
        systemCode: [
          { required: true, message: '请选择系统名称', trigger: 'change' }
        ]
      }

    }
  },
  mounted() {
    if (this.$route_query.id) {
      this.detailApi(this.$route_query.id)
      this.roleMenu = this.getRoleMenuTreeselect(this.$route_query.id)
    } else {
      this.getMenuTreeselect()
    }
    this.getDictMixins('sysNormalDisableOptions', 'sys_normal_disable')
    // this.getSysNormalDisable()// 状态数据
  },
  methods: {
    /**
     * @description: 根据角色ID查询菜单树结构
     * @Author: baoxuhui
     * @param {*} roleId
     * @return {*}
     */
    getRoleMenuTreeselect(roleId) {
      return methodGetApi('/system/menu/roleMenuTreeSelect/' + roleId).then((response) => {
        this.menuOptions = response.menus
        return response
      })
    },
    /**
     * @description: 默认菜单
     * @Author: baoxuhui
     * @return {*}
     */
    getMenuTreeselect() {
      methodGetApi('/system/menu/treeselect').then((response) => {
        this.menuOptions = response.data
      })
    },

    /**
     * @description:  树权限（展开/折叠）
     * @Author: baoxuhui
     * @param {*} value
     * @param {*} type
     * @return {*}
     */
    handleCheckedTreeExpand(value, type) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    /**
     * @description:  树权限（全选/全不选）
     * @Author: baoxuhui
     * @param {*} value
     * @param {*} type
     * @return {*}
     */
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    /**
     * @description: 树权限（父子联动）
     * @Author: baoxuhui
     * @param {*} value
     * @param {*} type
     * @return {*}
     */
    handleCheckedTreeConnect(value, type) {
      this.form.menuCheckStrictly = !!value
    },
    /**
     * @description: 菜单选中
     * @Author: baoxuhui
     * @return {*}
     */
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /**
    * @description: 保存
    * @Author: baoxuhui
    * @param {*} formName
    * @return {*}
    */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.menuIds = this.getMenuAllCheckedKeys()
          let url = null; let type = null
          if (this.$route_query.id) {
            url = '/system/role/edit'
            type = '修改'
          } else {
            url = '/system/role'
            type = '新增'
          }
          this.saveOrUpdateMixins(url, this.form, type)
        }
      })
    },

    /**
     * @description: 调取详情
     * @Author: baoxuhui
     * @return {*}
     */
    detailApi(id) {
      const url = '/system/role/' + id
      this.getDetailMixins(url)
    },
    /**
     * @description: 详情回显
     * @Author: baoxuhui
     * @param {*} id
     * @return {*}
     */
    formDetail(res) {
      const data = res.data
      this.form = data
      this.$nextTick(() => {
        this.roleMenu.then((res) => {
          this.$refs.menu.setCheckedKeys(res.checkedKeys)
        })
      })
      this.formLoading = false
    }

  }
}
</script>
